//
//  WLSocketBlockWorker.m
//  WanLian
//
//  Created by 123456 on 2019/1/4.
//  Copyright © 2019 wanlian. All rights reserved.
//

#import "WLSocketBlockWorker.h"
#import "WLFileTransportHeadModel.h"
@interface WLSocketBlockWorker ()
@end
@implementation WLSocketBlockWorker
- (void)suspend {
    [self.currentSocket disconnect];
}
- (void)resume {
    WLWkSelf
    [self.currentSocket disconnect];
    [self connectWithFailBlock:^{
        self.requestModel.workingState = WLWorkingStateFail;
        if (weakSelf.fileTransportFailureBlock) {
            weakSelf.fileTransportFailureBlock(@"连接失败", FileTransportErrorTypeConnectFail);
        }
    }];
}

- (void)cancel {
    [self.currentSocket disconnect];
    self.curHeadModel.currentSendIndex = -1;
}

- (void)sendFileDataWithHeadModel:(WLFileTransportHeadModel *)headModel {
    if (headModel.currentSendIndex < headModel.totalNum) {
        /*
        if (self.fileHandle == nil) {
            self.fileHandle = [NSFileHandle fileHandleForReadingAtPath:headModel.fileURL.path];
        }
        if (self.fileHandle && !flag) {
            
            if (self.curHeadModel == nil) {
                self.curHeadModel = headModel;
            }
            
            headModel.offset = headModel.blockIndex * headModel.blockSizeUnit + headModel.currentSendIndex * headModel.sendSizeUnit;
            [self.fileHandle seekToFileOffset:headModel.offset];
            NSData *sendData = [self.fileHandle readDataOfLength:headModel.sendSizeUnit];
            NSData *fileData = [self.requestModel getTransmitDataWithSendData:sendData blockIndex:self.curHeadModel.blockIndex];
            NSData *transmitData = [self configHeadProtocolWithData:fileData];
            NSLog(@"sendFileDataWithHeadModel %ld index == %d offset == %ld", sendData.length,headModel.currentSendIndex, headModel.offset);
            [self.currentSocket writeData:transmitData withTimeout:SocketTimeOut tag:WriteFileDataTag];
        }
        */
        if (self.localFileHandle == nil) {
            WLWkSelf
            self.localFileHandle = [WLLocalFileHandle fileHandleForReadingAtPath:headModel.mediaLocalURL isReadyBlock:^(BOOL isReady) {
                if (isReady == YES) {
                    [weakSelf sendFileDataWithHeadModel:headModel];
                }else {
                    if (weakSelf.fileTransportFailureBlock) {
                        weakSelf.fileTransportFailureBlock(@"读取数据失败", FileTransportReadingError);
                    }
                }
            }];
            return;
        }
        if (!flag) {
            headModel.offset = headModel.blockIndex * headModel.blockSizeUnit + headModel.currentSendIndex * headModel.sendSizeUnit + headModel.currentSize;
            NSData *sendData = [self.localFileHandle readDataAtOffset:headModel.offset lentgth:headModel.sendSizeUnit];
            headModel.size = sendData.length;
            NSData *fileData = [self.requestModel getTransmitDataWithSendData:sendData blockIndex:self.curHeadModel.blockIndex];
            NSData *transmitData = [self configHeadProtocolWithData:fileData];
            LHLog(@"sendFileDataWithHeadModel %ld index == %d offset == %ld  sendData.lenght = %ld, fileData.Length = %ld", sendData.length,headModel.currentSendIndex, headModel.offset, sendData.length, fileData.length);
            [self.currentSocket writeData:transmitData withTimeout:SocketTimeOut tag:WriteFileDataTag];
        }
    }
}



#pragma mark - GCDAsyncSocketDelegate
/**
 * Called when a socket connects and is ready for reading and writing.
 * The host parameter will be an IP address, not a DNS name.
 **/
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    [super socket:sock didConnectToHost:host port:port];
    if (sock == self.currentSocket) {
        [self sendFileDataWithHeadModel:self.curHeadModel];
    }
}

/**
 * Called when a socket has completed reading the requested data into memory.
 * Not called if there is an error.
 **/
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    [super socket:sock didReadData:data withTag:tag];
    if (tag == WriteFileDataTag) {
        if (self.parser == nil) {
            self.parser = [[WLSocketPacketParser alloc] initWithParserResultBlock:^(NSDictionary *msgDict, NSData *fileData, WLParserStatus status) {
                if (status == WLParserStatusSucess) {
                    NSDictionary *dictionary = msgDict;
                    WLSocketModel *messageModel = [WLSocketModel mj_objectWithKeyValues:dictionary];
                    if ([messageModel.type isEqualToString:DEVICE_FILE_UPLOAD_RSP]) {
                        [self clearTimer];
                        if (self.fileTransportCompleteBlock) {
                            self.fileTransportCompleteBlock();
                        }
                    }
                }
            }];
            [self.parser readData:data withSocket:sock tag:tag];
        }
    }
}


/**
 * Called when a socket has completed writing the requested data. Not called if there is an error.
 **/
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
    [super socket:sock didWriteDataWithTag:tag];
    static int index = 0;
    LHLog(@"didWriteDataWithTag == %ld, index == %d", tag, self.curHeadModel.currentSendIndex);
    index ++;
    self.curHeadModel.currentSendIndex ++;
    if (self.curHeadModel.currentSendIndex == self.curHeadModel.totalNum) {//发送完成
        self.curHeadModel.sendedSize = self.curHeadModel.bs;
    } else {
        [self sendFileDataWithHeadModel:self.curHeadModel];
        self.curHeadModel.sendedSize = self.curHeadModel.currentSendIndex * self.curHeadModel.sendSizeUnit;
    }
    if (self.fileTransportingBlock) {
        self.fileTransportingBlock();
    }
    [self.currentSocket readDataWithTimeout:SocketTimeOut tag:tag];
}
- (void)sendComplete {
    [self cancel];
}

@end
